﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

using ETRoboConTrakingSystem;

namespace ETRobocon.RaceTraking.GamePresentation
{

    /// <summary>
    /// UserControlRunnerStatus.xaml の相互作用ロジック
    /// </summary>
    public partial class UserControlRunnerStatus : UserControl, IRunnerStatus
    {
        [ImportMany(typeof(IRunnerStatusFireworksView))]
        public Lazy<IRunnerStatusFireworksView, IDictionary<string, object>>[] runnerStatusFireworksViews { get; set; }
        private IRunnerStatusFireworksView statusFireworksView { get; set; }

        [ImportMany(typeof(IClearMarksBuilder))]
        public Lazy<IClearMarksBuilder, IDictionary<string,object>>[] clearMarksBuilders { get; set; }
        private IClearMarksBuilder clearMarksBuilder { get; set; }

        private Dictionary<string, IClearMarkEffectView> clearMarks = new Dictionary<string, IClearMarkEffectView>();

        private List<ClearStatusPanelControl> clearStatusPanels = new List<ClearStatusPanelControl>();
        public List<ClearStatusPanelControl> MyClearStatusPanels { get { return clearStatusPanels; } }

        public UserControlRunnerStatus()
        {
            InitializeComponent();

            // ここではComposePartsが必要らしい
            var container = AppDomain.CurrentDomain.GetData("CurrentCompositionContainer") as CompositionContainer;
            container.ComposeParts(this);

            clearStatusPanels.Add(ClearStatusPanel0);
            clearStatusPanels.Add(ClearStatusPanel1);
            clearStatusPanels.Add(ClearStatusPanel2);
            clearStatusPanels.Add(ClearStatusPanel3);

            clearStatusPanels.Add(ClearStatusPanel4);
            clearStatusPanels.Add(ClearStatusPanel5);
            clearStatusPanels.Add(ClearStatusPanel6);
            clearStatusPanels.Add(ClearStatusPanel7);
            clearStatusPanels.Add(ClearStatusPanel8);
        }

        /// <summary>
        /// 走行時＆終了時に表示する花火表示を組み込む
        /// このメソッドは、CourseNameStatusをセット後にコールすること
        /// </summary>
        public void BuildFireworksView()
        {
            string compareWord = "";
            if ( this.CourseNameStatus.CompareTo(@"インコース") == 0)
            {
                compareWord = "In";
            }
            else
            {
                compareWord = "Out";
            }
            if (statusFireworksView == null)
            {
                // BuildClearMarks();
                foreach (var export in this.runnerStatusFireworksViews)
                {
                    if (export.Metadata["Kind"].ToString().StartsWith(compareWord))
                    {
                        {
                            statusFireworksView = export.Value;
                            UserControl fireworksView = statusFireworksView as UserControl;
                            this.CourseCanvase.Children.Add(fireworksView);
                            Canvas.SetTop(fireworksView, statusFireworksView.PositionTop);
                            Canvas.SetLeft(fireworksView, statusFireworksView.PositionLeft);
                            HiddenRunnerStatus();

                            break;
                        }
                    }

                }
            }
        }

        public void BuildClearMarks(List<ClearMarkSpec> clearMarkSpecs)
        {
            string compareWord = "";
            if (this.CourseNameDisplay.Text.CompareTo(@"インコース") == 0)
            {
                compareWord = "In";
            }
            else
            {
                compareWord = "Out";
            }
            foreach (var export in this.clearMarksBuilders)
            {
                if (export.Metadata["Kind"].ToString().StartsWith(compareWord))
                {
                    clearMarksBuilder = export.Value;
                    break;
                }
            }
            List<IClearMarkEffectView> views = clearMarksBuilder.Create(clearMarkSpecs.Count);
            int index = 0;
            foreach (var cmSpec in clearMarkSpecs)
            {
//                UserControlClearMark cm = new UserControlClearMark();
//                IClearMarkEffectView cmView = views[index++];
//                UserControl cm = cmView as UserControl;

//                this.CourseCanvase.Children.Add(cm);
//                Canvas.SetTop(cm, cmSpec.CanvasTop);
//                Canvas.SetLeft(cm, cmSpec.CanvasLeft);
//                cmView.Reset();
                IClearMarkEffectView cmView = clearStatusPanels[index++];
                cmView.MarkerName = cmSpec.Name;
                UserControl cmViewControl = cmView as UserControl;
                cmViewControl.Visibility = System.Windows.Visibility.Visible;
                
                cmView.Reset();

                clearMarks.Add(cmSpec.Key, cmView);
            }
        }

        public string CourseNameStatus
        {
            set
            {
                this.CourseNameDisplay.Text = value;
            }
            get
            {
                return this.CourseNameDisplay.Text;
            }
        }

        private string _courseImage;
        public string CourseImageFile
        {
            get { return _courseImage; }
            set
            {
                _courseImage = value;
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                string source = this.GetType().Namespace + ".Assets." + _courseImage;
                System.IO.Stream stream = assembly.GetManifestResourceStream(source);
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = stream;
                bi.EndInit();
                this.CourseImage.Fill = new ImageBrush(bi);
                CourseImage.Opacity = _imageOpacity;
            }
        }

        private double _imageOpacity = 1.0;

        public double CourseImageOpachity
        {
            set
            {
                CourseImage.Opacity = value;
            }
            get
            {
                return CourseImage.Opacity;
            }
        }

        public RunnerInfo CurrentRunner
        {
            get
            {
                return this.CurrentTeamInfo.CurrentRunner;
            }
        }

        public RunnerTimerCounterUserControl TimeCounter
        {
            get
            {
                return this.CurrentTeamInfo.TimeCounter;
            }
        }

        private delegate void NonArgumentDelegater();
        public void ResetRunnerTimerCounter()
        {
            this.Dispatcher.BeginInvoke(new NonArgumentDelegater(this.CurrentTeamInfo.ResetTimerCounter), new object[] { });
//            this.CurrentTeamInfo.ResetTimerCounter();
        }

        public void ResetClearedMarks()
        {
            foreach (var key in clearMarks.Keys)
            {
                var cm = clearMarks[key];
                cm.Reset();
            }
        }

        private delegate void ShowRunnerStatusDelegater(string status);

        public void ShowRunnerStatus(string status)
        {
            this.Dispatcher.BeginInvoke(new ShowRunnerStatusDelegater(this.showRunnerStatusFunc), new object[] { status });
        }
        private void showRunnerStatusFunc(string status)
        {
            statusFireworksView.RunnerStatus = status;
            statusFireworksView.ShowFireworks();
        }
        public void HiddenRunnerStatus()
        {
            statusFireworksView.HideFireworks();
        }

        public void ShowCleardMark(string key, int level, bool on)
        {
            var cm = clearMarks[key];
            if (cm != null)
            {
                cm.Fire(level, on);
//                if (level == 1)
  //              {
    //                cm.ClearMark1Visibility(on);
      //          }
        //        else if (level == 2)
          //      {
            //        cm.ClearMark2Visibility(on);
              //  }
            }
        }

        public IDifficultPointStatus DifficultPointStatus
        {
            get { return myDifficultPointStatus; }
        }


        // 九州大会暫定

        public void ShowDriftCourse(string couseName, bool on)
        {
            string statement = "Drift:A";
            if (couseName == "B")
            {
                statement = "Drift：B";
            }
            tbDriftCourseName.Text = statement;
            
            if (on)
            {
                System.Windows.Media.Animation.Storyboard sb = new System.Windows.Media.Animation.Storyboard();
                tbDriftCourseName.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                tbDriftCourseName.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        #region IRunnerStatus Members

        public ITimerCounter RunnerTimerCounter
        {
            get
            {
                return this.CurrentTeamInfo.TimeCounter;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        #endregion



    }


}
